package com.bz.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.bz.common.JwtTokenUtil;
import com.bz.common.RedisServiceUtil;
import com.bz.common.ResponseDto;
import com.bz.common.ResponseUtils;
import com.bz.common.UserConfig;

@Component
public class AuthenctiationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    @Autowired
    private JwtTokenUtil     jwtTokenUtil;

    @Autowired
    private RedisServiceUtil redisServiceUtil;

    // 加密秘钥
    @Value("${jwt.validity}")
    private long             validity;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        AuthUserDto authUserDto = (AuthUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String token = jwtTokenUtil.sign(authUserDto.getUsername());

        // 登录成功后保存redis
        // 保存进redis
        redisServiceUtil.set(UserConfig.getUserKey(authUserDto.getUsername()), JSON.toJSONString(UserConfig.convertUser(authUserDto)),
            validity);

        ResponseUtils.setResponse(response, new ResponseDto<String>(token));
    }
}
